<template>
  <div>
    <el-upload
      ref="upload"
      name="file"
      list-type="picture-card"
      accept="image/*"
      action="https://addr.aikucun.com/v1.0/upload/file"
      :class="{hide: imgList.length == 4}"
      :before-upload="beforeUpload"
      :on-remove="handleFileRemove"
      :on-preview="handlePictureCardPreview"
      :on-success="handleFileSuccess"
      :on-change="handleFileChange"
      :limit="4"
      :file-list="imgList"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog :visible.sync="picDialogVisible" title="图片预览">
      <img width="100%" :src="picDialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'CommonUpload',
  props: {
    imgList: {
      type: Array,
      default: () => []
    },
    onUpdate: {
      type: Function,
      default: () => {}
    }
  },
  data() {
    return {
      picDialogImageUrl: '',
      picDialogVisible: false
    }
  },
  methods: {
    // 图片上传处理开始
    beforeUpload(file) {
      const isImg = file.type && file.type.indexOf('image/') === 0
      if (!isImg) {
        this.$message.error('请选择图片文件!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过2MB!')
      }
      return isImg && isLt2M
    },
    handlePictureCardPreview(file) {
      this.picDialogImageUrl = file.url
      this.picDialogVisible = true
    },
    handleFileRemove(file) {
      this.imgList = this.imgList.filter(item => item.url !== file.url)
      // this.onUpdate()
    },
    handleFileChange(file, fileList) {
      // if (fileList.length == 4) {
      // this.rules.imgList = []
      // this.$refs['uploadElement'].clearValidate()
      // }
    },
    handleFileSuccess(res, file) {
      const { code, message, data } = res
      if (code === 0) {
        this.imgList.push({
          uid: file.uid,
          url: data.filename[0]
        })
        // this.onUpdate()
      } else {
        this.$message.error(message)
      }
    }
  }
}
</script>

<style lang="scss">
  .hide {
    .el-upload--picture-card {
      display: none !important;
    }
  }
</style>
